<template>
  <div>
      <div class="course-info-div">

        <el-form ref="form" :model="courseInfo" label-width="120px">
            <el-form-item label="课程名称：" class="course-form-item">
                <el-input v-model="courseInfo.courseName"></el-input>

            </el-form-item>

            <el-form-item label="课程介绍：" class="course-form-item">
                <el-input
                type="textarea"
                :rows="3"
                
                placeholder="请输入内容："
                v-model="courseInfo.courseDesc">
                </el-input>
            </el-form-item>

            <el-form-item label="设置学期时间：" class="course-form-item">
                        <el-date-picker
                        v-model="time"
                        type="daterange"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                        </el-date-picker>
            </el-form-item>

        

            <el-form-item label="封面：">
                    <el-radio-group v-model="courseImgCheckType">
                        <el-radio-button label=1>通用模板</el-radio-button>
                        <el-radio-button label=2>个人上传</el-radio-button>
                    </el-radio-group>
                    <div v-show="!courseImgsTmplateIsShow">

                        <el-upload
                        class="avatar-uploader"
                        action
                        :show-file-list="false"
                        v-model="courseInfo.courseImgUrl"
                        :before-upload="beforeAvatarUpload"
                        :http-request="getImgPutUrlFromSts"
                        >
                        <img v-if="uploadImgUrl" :src="uploadImgUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>

                        <el-tag type="info">请注意上传图片比例问题，请一定要让宽度 > 高度。最好比例为9：5</el-tag>
                    </div>


                   
            </el-form-item>
            <div style="margin-top:2%;">
                        
                        <div class="course_imgs_div" v-show="courseImgsTmplateIsShow">
                            <div class="course_img_card" 
                            
                            v-for="imgUrl, index in courseImgUrls"
                            :key="index"
                            @click="checkTheCard(index)">
                                <img :src="imgUrl" alt="" :id="'course_img_card'+index">
                            </div>

                        </div>
                </div>
            

                <el-form-item label="添加班级：">
                    <el-transfer v-model="courseInfo.classIds" :titles="['可选班级', '已选班级']"
                    :data="myClassInfo"></el-transfer>
                </el-form-item>
        </el-form>

         <el-divider></el-divider>
         <el-tag type="warning" >创建后会返回 课程URL，您可以发送该URL给学生自行添加</el-tag>
         <el-button style="margin-left:2%;" type="primary" size="small" @click="createCourse">开始创建</el-button>
         <div v-if="socketMsgIsBack">
             <div v-for="result,index in results" :key="index" style="margin-top:1%;">
                <el-tag type="success">
                    {{result.info}}
                </el-tag>
             </div>
         </div>
         
         <div v-loading="courseURlLoadingShow" v-if="courseUrlShow" style="margin-top:2%;; width: 800px">
            
             <el-tag type="success">
            课程链接：
            </el-tag>
            <el-tag type="success">
                {{host}}/api/course/bind/{{courseUrl}}
            </el-tag>
         </div>

      </div>

  </div>
</template>

<script>
import * as COURSEAPI from '../../api/course/index'
import * as CLASSAPI from '../../api/class/index'
import * as FILEAPI from '../../api/file/index'
import {Storage} from '../../storage'
import UUID from 'uuidjs';

export default {
    data() {
        return {
            host:'',
            courseImgUrls: ['https://nothing-link.oss-cn-beijing.aliyuncs.com/course1.png', 
                            'https://nothing-link.oss-cn-beijing.aliyuncs.com/course2.png', 
                            'https://nothing-link.oss-cn-beijing.aliyuncs.com/course3.png',
                            'https://nothing-link.oss-cn-beijing.aliyuncs.com/course4.png',
                            'https://nothing-link.oss-cn-beijing.aliyuncs.com/course5.png',
                            'https://nothing-link.oss-cn-beijing.aliyuncs.com/course6.png',],
            curCheckImgUrl: "",
            uploadImgUrl: "",
            courseInfo: {
                courseName: "",
                courseDesc: "",
                classIds: [],
                createTime: '',
                endTime:'',
                courseImgUrl:'',
            },
            time:[],
            courseUrl:"",
            activeName:"first",
            courseImgCheckType:1,
            courseImgsTmplateIsShow:true,
            myClassInfo: [],
            courseUrlShow:false,
            courseURlLoadingShow:false,
            socket:'',
            teaId:'',
            results:[
            ],
            socketMsgIsBack: false
        }
    },
    methods: {
        handleClick(tab, event) {
            console.log(tab, event);
        },
        checkTheCard(index) {
            console.log(this.courseImgUrls.length)
            for(let i = 0; i < this.courseImgUrls.length; i++) {
                if(i == index) {
                    document.getElementById(`course_img_card${i}`).style.border = "2px solid red";
                }else {
                    document.getElementById(`course_img_card${i}`).style.border = "none"
                }
            }
            
            this.courseInfo.courseImgUrl = this.courseImgUrls[index]
        },
        handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG && !isPNG) {
                this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return (isJPG || isPNG) && isLt2M;
        },
        createCourse() {
            this.courseURlLoadingShow = true
            this.courseUrlShow = true
            this.socketMsgIsBack = true


            for(let i = 0; i < this.time.length; i++) {
                if(i == 0) this.courseInfo.createTime = this.time[i]
                else this.courseInfo.endTime = this.time[i]

            }

            COURSEAPI.createCourse(this.courseInfo).then(res => {
                console.log(res.data)
                if(res.code == 200) {
                    this.courseUrl = res.data.course.courseUrl
                    this.courseURlLoadingShow = false
                }else {
                    this.$notify.error({
                    title: res.data.error,
                    message: err,
                });
                }
            }).catch(err => {
                this.$notify.error({
                    title: '网路错误，或者服务器宕机',
                    message: err,
                });
            })
        },
        getImgPutUrlFromSts(option) {
            let fileName = UUID.generate()
            let fileType = option.file.type.split("/")[1]
            FILEAPI.getImgUrl(fileName, fileType).then(res => {

                let url = res.data.URL

                const oReq = new XMLHttpRequest();
                oReq.open('PUT', url, true);
                oReq.setRequestHeader("Content-Type", "application/octet-stream")
                oReq.setRequestHeader("x-oss-meta-author", "nothing")
                oReq.send(option.file);
                oReq.onload = () => {
                    this.uploadImgUrl = `https://nothing-link.oss-cn-beijing.aliyuncs.com/${fileName}.${fileType}`;
                    this.courseInfo.courseImgUrl = `https://nothing-link.oss-cn-beijing.aliyuncs.com/${fileName}.${fileType}`;
                };
            }).catch((error) => {
                this.$notify.error({
                    title: '网路错误，或者服务器宕机',
                    message: error,
                });
            });
        },
        initSocket(teaId) {
            if(typeof(WebSocket) === "undefined"){
                alert("您的浏览器不支持socket")
            }else{
                // 实例化socket
                this.socket = new WebSocket(`ws://127.0.0.1:8900/courseNew/${teaId}`)
                // 监听socket连接
                this.socket.onopen = this.onopen
                // 监听socket错误信息
                this.socket.onerror = this.onerror
                // 监听socket消息
                this.socket.onmessage = this.ongetMessage
            }
        },
        onopen() {
            console.log("ws on open")
        },
        onerror() {
            console.log("ws on error")
        },
        ongetMessage(msg) {
            console.log(msg)
            let data = JSON.parse(msg.data);
            console.log(data)
            //如果是心跳检测的话，那么不予例会
            if(data.code == 201) return;
            
            this.results.push({
                info:data.data.msg
            })  
        },
        onclose() {
            this.socket.close()
            console.log("socket已经关闭")
        }
    },
    watch: {
        courseImgCheckType(val) {
            if(val == 2) {
                this.courseImgsTmplateIsShow = false
            }else {
                this.courseImgsTmplateIsShow = true
            }
            
        },
    },
    mounted() {
        let host = window.location.host;
        this.host = host
        this.teaId = Storage.get("tea").teaId
        this.initSocket(this.teaId)

        CLASSAPI.getAllClassInfo(1, 2).then(res => {
            
            res.data.classInfos.forEach(classInfo => {
                this.myClassInfo.push(
                    {
                        key:classInfo.classId,
                        label:classInfo.classRealName
                    }
                )
            });
        }).catch(err => {
            this.$message.error('网络错误！')
        })
    },
    destroyed () {
        // 销毁监听
        this.onclose()
    }
}
</script>

<style>
.course-info-div {
    min-width: 600px;
    margin: 2%;
}
.course-form-item {
    width: 400px;
}

.course_imgs_div {
    display: flex;
    width: 100%;
    flex-wrap: wrap;

    /* background: black; */
}

.course_img_card {
    /* width: 270px;
    height: 152px; */
    width: 360px;
    height: 200px;
    margin-bottom: 1%;
    display: flex;
    justify-content: center;
}

.course_img_card > img {
    /* width: 100%;
    height: 100%; */
    width: 270px;
    height: 152px; 

    transition: width 0.4s, height 0.3s;
    cursor: pointer;

}

.course_img_card > img:hover {
    width: 355px;
    height: 200px;
}

  .avatar-uploader .el-upload {
    margin-top: 2%;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #FED049;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 270px;
    height: 152px; 
    line-height: 152px;
    text-align: center;
  }

  .avatar {
    width: 270px;
    height: 152px; 
    display: block;
  }
</style>